<template>
  <div class="collection-box-view-content">
    <div class="add-todo-solo-section">
        <input 
          type="text" 
          class="todo-input" 
          placeholder="添加一个无日期的任务到收集箱..." 
          v-model="newInboxTodoText"
          @keyup.enter="handleAddInboxTodo"
        >
        <button @click="handleAddInboxTodo" class="add-button">添加</button>
    </div>

    <div class="search-section-inbox">
      <input 
        type="text" 
        v-model="searchQueryInbox" 
        placeholder="搜索收集箱内的任务..." 
        class="search-input-inbox"
      >
    </div>

    <div class="controls-bar">
      <div class="batch-actions-left">
        <input 
          type="checkbox" 
          :checked="isAllSelected && searchedFilteredAndSortedInboxTodos.length > 0"
          @change="toggleSelectAll"
          id="select-all-inbox-todos"
          title="全选/取消全选"
          class="select-all-checkbox"
        >
        <label for="select-all-inbox-todos" class="select-all-label">全选</label>
        <button @click="handleBatchDelete" :disabled="!hasSelectedTodos" class="batch-action-button delete">
          <span class="button-icon">&#xE74D;</span> 删除选中
        </button>
        <button @click="handleBatchArchive" :disabled="!hasSelectedTodos" class="batch-action-button archive">
          <span class="button-icon">&#xE7B8;</span> 归档选中
        </button>
      </div>
      <div class="filter-sort-controls">
        <div class="filter-controls">
          <span class="controls-label">筛选:</span>
          <button @click="setFilter('all')" :class="{ 'active': filterStatus === 'all' }">全部状态</button>
          <button @click="setFilter('active')" :class="{ 'active': filterStatus === 'active' }">未完成</button>
          <button @click="setFilter('completed')" :class="{ 'active': filterStatus === 'completed' }">已完成</button>
        </div>
        <div class="filter-priority-controls">
          <span class="controls-label">优先级:</span>
          <button @click="setFilterPriorityInbox('all')" :class="{ 'active': filterPriorityInbox === 'all' }">全部</button>
          <button @click="setFilterPriorityInbox(PRIORITIES.HIGH)" :class="{ 'active': filterPriorityInbox === PRIORITIES.HIGH }">
            <span class="priority-dot-filter" :style="{ backgroundColor: getPriorityColor(PRIORITIES.HIGH) }"></span>{{ getPriorityText(PRIORITIES.HIGH) }}
          </button>
          <button @click="setFilterPriorityInbox(PRIORITIES.MEDIUM)" :class="{ 'active': filterPriorityInbox === PRIORITIES.MEDIUM }">
            <span class="priority-dot-filter" :style="{ backgroundColor: getPriorityColor(PRIORITIES.MEDIUM) }"></span>{{ getPriorityText(PRIORITIES.MEDIUM) }}
          </button>
          <button @click="setFilterPriorityInbox(PRIORITIES.LOW)" :class="{ 'active': filterPriorityInbox === PRIORITIES.LOW }">
            <span class="priority-dot-filter" :style="{ backgroundColor: getPriorityColor(PRIORITIES.LOW) }"></span>{{ getPriorityText(PRIORITIES.LOW) }}
          </button>
          <button @click="setFilterPriorityInbox(PRIORITIES.NONE)" :class="{ 'active': filterPriorityInbox === PRIORITIES.NONE }">
            <span class="priority-dot-filter" :style="{ backgroundColor: getPriorityColor(PRIORITIES.NONE) }"></span>{{ getPriorityText(PRIORITIES.NONE) }}
          </button>
        </div>
        <div class="sort-controls">
          <span class="controls-label">排序:</span>
          <CustomSelect 
            v-model="currentSortOrder"
            :options="sortOptions"
            placeholder="选择排序方式"
            class="sort-select-wrapper" />
        </div>
      </div>
    </div>
    
    <div class="todo-list-section">
      <ul class="todo-list" v-if="paginatedInboxTodos.length > 0">
        <li 
          v-for="todo in paginatedInboxTodos" 
          :key="todo.id" 
          :class="['todo-item', { 'completed': todo.completed, 'selected-for-batch': selectedTodoIds.includes(todo.id) }]" 
          :data-todoid="todo.id"
          @contextmenu.prevent="openCollectionContextMenu(todo, $event)"
        >
          <input 
            type="checkbox" 
            :id="'select-todo-' + todo.id" 
            class="todo-select-checkbox" 
            :checked="selectedTodoIds.includes(todo.id)" 
            @change="toggleTodoSelection(todo.id)"
          >
          <span 
            @click="handleToggleInboxTodo(todo.id)" 
            :class="['todo-status-icon', todo.completed ? 'completed-icon' : 'pending-icon']"
            :title="todo.completed ? '标记为未完成' : '标记为已完成'"
          >
             {{ todo.completed ? '&#xE930;' : '&#xE931;' }}
          </span>
          <span 
            class="priority-indicator"
            :style="{ backgroundColor: getPriorityColor(todo.priority) }"
            :title="'优先级: ' + getPriorityText(todo.priority)"
          ></span>
          <label 
            v-if="editingTodoId !== todo.id" 
            :for="'select-todo-' + todo.id" 
            class="todo-label" 
            @dblclick="startEditing(todo)"
          >
            {{ todo.text }}
          </label>
          <input 
            v-else 
            type="text" 
            v-model="editingTodoText" 
            class="todo-edit-input" 
            @blur="saveEdit(todo.id)" 
            @keyup.enter="saveEdit(todo.id)" 
            @keyup.esc="cancelEdit"
            v-focus
          />
        </li>
      </ul>
      <p v-else class="empty-list-message">
        <span v-if="(Array.isArray(getInboxTodos) ? getInboxTodos : []).length === 0 && !searchQueryInbox && filterStatus === 'all' && filterPriorityInbox === 'all'">
          收集箱是空的！快去添加一些无日期的任务吧。
        </span>
        <span v-else>
          当前筛选条件下没有匹配的任务。请尝试调整搜索词、状态或优先级筛选器。
        </span>
      </p>
    </div>

    <div class="pagination-controls-inbox" v-if="totalPagesInbox > 1">
      <button @click="prevInboxPage" :disabled="currentPageInbox === 1" class="pagination-button-inbox">上一页</button>
      <span class="pagination-info-inbox">第 {{ currentPageInbox }} / {{ totalPagesInbox }} 页</span>
      <button @click="nextInboxPage" :disabled="currentPageInbox === totalPagesInbox" class="pagination-button-inbox">下一页</button>
    </div>

    <div class="bottom-bar">
      <span class="status-text">
        选中 {{ selectedTodoIds.length }} / {{ searchedFilteredAndSortedInboxTodos.length }} 个任务。
        当前列表共 {{ searchedFilteredAndSortedInboxTodos.length }} 个，{{ completedSearchedFilteredInboxTodosCount }} 个已完成。
      </span>
      <div class="priority-legend-container">
        <div class="priority-legend">
          <div class="legend-item">
            <span class="legend-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.HIGH) }"></span>
            <span>{{ getPriorityText(PRIORITIES.HIGH) }}</span>
          </div>
          <div class="legend-item">
            <span class="legend-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.MEDIUM) }"></span>
            <span>{{ getPriorityText(PRIORITIES.MEDIUM) }}</span>
          </div>
          <div class="legend-item">
            <span class="legend-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.LOW) }"></span>
            <span>{{ getPriorityText(PRIORITIES.LOW) }}</span>
          </div>
          <div class="legend-item">
            <span class="legend-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.NONE) }"></span>
            <span>{{ getPriorityText(PRIORITIES.NONE) }}</span>
          </div>
        </div>
      </div>
    </div>

    <div 
      v-if="collectionContextMenu.visible"
      ref="collectionContextMenuRef"
      class="context-menu"
      :style="{ top: collectionContextMenu.top + 'px', left: collectionContextMenu.left + 'px' }"
      @click.stop
      v-click-outside="closeCollectionContextMenu"
    >
      <div 
        class="context-menu-item priority-submenu-container"
        ref="prioritySubmenuParentRef"
        @mouseenter="openPrioritySubmenu"
        @mouseleave="scheduleClosePrioritySubmenu"
      >
        <span>设置优先级</span>
        <span class="submenu-arrow">&#xE76C;</span>
      </div>
      <div class="context-menu-item" @click="assignDateFromCollectionContextMenu">分配日期</div>
      <div class="context-menu-item" @click="editCollectionContextTodo">编辑</div>
      <div class="context-menu-item" @click="archiveCollectionContextTodo">归档</div>
      <div class="context-menu-item" @click="deleteCollectionContextTodo">删除</div>
    </div>

    <!-- Priority Submenu for CollectionBox -->
    <div
      v-if="prioritySubmenu.visible"
      ref="prioritySubmenuRef"
      class="priority-submenu" 
      :class="{ 'submenu-positioned-left': prioritySubmenu.isPositionedLeft }"
      :style="prioritySubmenu.style"
      @mouseenter="clearClosePrioritySubmenuTimer"
      @mouseleave="scheduleClosePrioritySubmenu(true)"
      @click.stop
    >
          <div class="context-menu-item" @click="setCollectionContextMenuTodoPriority(PRIORITIES.HIGH)">
            <span class="priority-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.HIGH) }"></span> 高
          </div>
          <div class="context-menu-item" @click="setCollectionContextMenuTodoPriority(PRIORITIES.MEDIUM)">
            <span class="priority-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.MEDIUM) }"></span> 中
          </div>
          <div class="context-menu-item" @click="setCollectionContextMenuTodoPriority(PRIORITIES.LOW)">
            <span class="priority-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.LOW) }"></span> 低
          </div>
          <div class="context-menu-item" @click="setCollectionContextMenuTodoPriority(PRIORITIES.NONE)">
            <span class="priority-dot" :style="{ backgroundColor: getPriorityColor(PRIORITIES.NONE) }"></span> {{ getPriorityText(PRIORITIES.NONE) }}
          </div>
    </div>

    <MiniCalendar
      ref="inboxMiniCalendar"
      :initialDate="datePickerInitialDate"
      @date-selected="handleDateSelectedForInboxTodo"
      @close="closeDatePickerForInboxTodo"
    />

  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import Vue from 'vue'; 
import { getPriorityText, getPriorityColor, getPriorityIcon, PRIORITIES } from '../utils/priorityUtils';
import { calculateContextMenuPosition, calculateSubmenuPosition } from '../utils/contextMenuUtils';
import MiniCalendar from '../components/MiniCalendar.vue';
import CustomSelect from '@/components/CustomSelect.vue';

export default {
  name: 'CollectionBoxView',
  components: {
    MiniCalendar,
    CustomSelect
  },
  data() {
    return {
      newInboxTodoText: '',
      editingTodoId: null,
      editingTodoText: '',
      currentSortOrder: 'added_asc', 
      filterStatus: 'all',
      selectedTodoIds: [],
      collectionContextMenu: {
        visible: false,
        top: 0,
        left: 0,
        selectedTodo: null,
        dimensions: { width: 160, height: 190 },
        isPushedLeft: false
      },
      prioritySubmenu: {
        visible: false,
        style: {},
        isPositionedLeft: false,
        dimensions: { width: 100, height: 130 },
        closeTimer: null
      },
      PRIORITIES: PRIORITIES,
      datePickerTargetTodoId: null,
      datePickerInitialDate: new Date(),
      searchQueryInbox: '',
      currentPageInbox: 1,
      itemsPerPageInbox: 10, // 每页显示的任务数
      filterPriorityInbox: 'all', // 'all', PRIORITIES.HIGH, etc.
      sortOptions: [
        { value: 'added_asc', text: '添加时间 (最早)' },
        { value: 'added_desc', text: '添加时间 (最新)' },
        { value: 'text_asc', text: '文本 (A-Z)' },
        { value: 'text_desc', text: '文本 (Z-A)' },
        { value: 'priority_desc', text: '优先级 (高到低)' },
        { value: 'priority_asc', text: '优先级 (低到高)' },
      ]
    };
  },
  computed: {
    ...mapGetters([
      'getInboxTodos' 
    ]),
    isAllSelected() {
      if (this.paginatedInboxTodos.length === 0) { // Check against current page items
        return false;
      }
      // Check if all items on the current page are selected
      const currentPageItemIds = this.paginatedInboxTodos.map(todo => todo.id);
      return currentPageItemIds.every(id => this.selectedTodoIds.includes(id));
    },
    hasSelectedTodos() {
      return this.selectedTodoIds.length > 0;
    },
    searchedFilteredAndSortedInboxTodos() {
      // Ensure getInboxTodos is treated as an array
      const rawTodos = Array.isArray(this.getInboxTodos) ? this.getInboxTodos : [];
      let todos = [...rawTodos]; 

      // 1. Apply search query
      if (this.searchQueryInbox) {
        todos = todos.filter(todo =>
          todo.text.toLowerCase().includes(this.searchQueryInbox.toLowerCase())
        );
      }

      // 2. Apply filter status
      if (this.filterStatus === 'active') {
        todos = todos.filter(todo => !todo.completed);
      } else if (this.filterStatus === 'completed') {
        todos = todos.filter(todo => todo.completed);
      }

      // 3. Apply priority filter
      if (this.filterPriorityInbox !== 'all') {
        todos = todos.filter(todo => todo.priority === this.filterPriorityInbox);
      }

      // 4. Apply sort order
      todos.sort((a, b) => {
        if (this.currentSortOrder === 'priority_desc') {
          return (b.priority || 0) - (a.priority || 0);
        } else if (this.currentSortOrder === 'priority_asc') {
          return (a.priority || 0) - (b.priority || 0);
        }
        switch (this.currentSortOrder) {
          case 'added_desc': return (b.id > a.id) ? 1 : ((a.id > b.id) ? -1 : 0);
          case 'added_asc':  return (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0);
          case 'text_asc':   return a.text.localeCompare(b.text);
          case 'text_desc':  return b.text.localeCompare(a.text);
          default: return 0;
        }
      });
      return todos;
    },
    totalPagesInbox() {
      return Math.ceil(this.searchedFilteredAndSortedInboxTodos.length / this.itemsPerPageInbox);
    },
    paginatedInboxTodos() {
      const startIndex = (this.currentPageInbox - 1) * this.itemsPerPageInbox;
      const endIndex = startIndex + this.itemsPerPageInbox;
      return this.searchedFilteredAndSortedInboxTodos.slice(startIndex, endIndex);
    },
    completedFilteredInboxTodosCount() { 
        return this.filteredAndSortedInboxTodos.filter(todo => todo.completed).length;
    },
    completedSearchedFilteredInboxTodosCount() {
      return this.searchedFilteredAndSortedInboxTodos.filter(todo => todo.completed).length;
    }
  },
  methods: {
    ...mapActions([
      'addInboxTodo',
      'toggleInboxTodo',
      'updateInboxTodoText', 
      'deleteInboxTodo',
      'archiveInboxTodo',
      'updateTodoPriority',
      'deleteBatchInboxTodos',
      'archiveBatchTodos',
      'moveInboxTodoToDate',
      'fetchInboxTodos'
    ]),
    getPriorityText,
    getPriorityColor,
    getPriorityIcon,
    setFilter(status) { 
      this.filterStatus = status;
      this.selectedTodoIds = [];
    },
    setFilterPriorityInbox(priority) {
      this.filterPriorityInbox = priority;
      // selectedTodoIds = []; // Potentially reset selection or not, based on desired UX
    },
    toggleSelectAll() {
      const currentPageItemIds = this.paginatedInboxTodos.map(todo => todo.id);
      if (this.isAllSelected) {
        // Unselect all items on the current page
        this.selectedTodoIds = this.selectedTodoIds.filter(id => !currentPageItemIds.includes(id));
      } else {
        // Select all items on the current page, ensuring no duplicates
        const newSelectedIds = new Set([...this.selectedTodoIds, ...currentPageItemIds]);
        this.selectedTodoIds = Array.from(newSelectedIds);
      }
    },
    toggleTodoSelection(todoId) {
      const index = this.selectedTodoIds.indexOf(todoId);
      if (index > -1) {
        this.selectedTodoIds.splice(index, 1);
      } else {
        this.selectedTodoIds.push(todoId);
      }
      this.closeCollectionContextMenu();
    },
    handleBatchDelete() {
      if (this.selectedTodoIds.length > 0) {
        this.deleteBatchInboxTodos(this.selectedTodoIds);
        this.selectedTodoIds = [];
      }
    },
    handleBatchArchive() {
      if (this.hasSelectedTodos) {
        console.log("[CollectionBoxView] handleBatchArchive: Archiving todos:", this.selectedTodoIds);
        this.archiveBatchTodos({ 
          todoIds: [...this.selectedTodoIds], 
          source: 'inbox' 
        });
        this.selectedTodoIds = [];
      }
    },
    handleAddInboxTodo() {
      if (this.newInboxTodoText.trim()) {
        this.addInboxTodo(this.newInboxTodoText.trim());
        this.newInboxTodoText = ''; 
      }
    },
    handleToggleInboxTodo(todoId) {
      this.toggleInboxTodo(todoId);
    },
    handleDeleteInboxTodo(todoId) {
      this.deleteInboxTodo(todoId);
    },
    handleArchiveTodo(todoId) { 
      this.archiveInboxTodo({ todoId });
    },
    openDatePickerForSelectedTodo(todoId) {
      this.datePickerTargetTodoId = todoId;
      this.datePickerInitialDate = new Date();
      this.$refs.inboxMiniCalendar.open();
    },
    closeDatePickerForInboxTodo() {
      this.datePickerTargetTodoId = null;
    },
    handleDateSelectedForInboxTodo(selectedDate) {
      if (this.datePickerTargetTodoId) {
        console.log(`[CollectionBoxView] handleDateSelectedForInboxTodo: Attempting to move todoId: ${this.datePickerTargetTodoId} to date:`, selectedDate);
        const todoToMove = this.getInboxTodos.find(t => t.id === this.datePickerTargetTodoId);
        console.log(`[CollectionBoxView] Found todo in inbox:`, JSON.parse(JSON.stringify(todoToMove)));
        this.moveInboxTodoToDate({ todoId: this.datePickerTargetTodoId, date: selectedDate });
        console.log(`[CollectionBoxView] moveInboxTodoToDate action called for todoId: ${this.datePickerTargetTodoId}`);
      }
    },
    startEditing(todo) {
      this.editingTodoId = todo.id;
      this.editingTodoText = todo.text;
    },
    saveEdit(todoId) {
      if (this.editingTodoId === todoId && this.editingTodoText.trim()) {
        this.updateInboxTodoText({ todoId, newText: this.editingTodoText.trim() });
      }
      this.cancelEdit();
    },
    cancelEdit() {
      this.editingTodoId = null;
      this.editingTodoText = '';
    },
    openCollectionContextMenu(todo, event) {
      this.collectionContextMenu.selectedTodo = todo;
      const { top, left, adjustedLeft } = calculateContextMenuPosition(event, this.collectionContextMenu.dimensions);
      this.collectionContextMenu.top = top;
      this.collectionContextMenu.left = left;
      this.collectionContextMenu.isPushedLeft = adjustedLeft;
      this.collectionContextMenu.visible = true;
      console.log(`[CollectionBoxView] openContextMenu: Opened for todo id: ${todo.id} at (${left}px, ${top}px). Pushed left: ${adjustedLeft}`);

      if (this.prioritySubmenu.visible) {
        this.prioritySubmenu.visible = false;
          }
    },
    closeCollectionContextMenu() {
      if (this.collectionContextMenu.visible) {
        console.log("[CollectionBoxView] closeCollectionContextMenu: Closing main context menu.");
      this.collectionContextMenu.visible = false;
      this.collectionContextMenu.selectedTodo = null;
        if (this.prioritySubmenu.visible) {
          this.prioritySubmenu.visible = false;
        }
      }
    },
    openPrioritySubmenu() {
      if (!this.$refs.prioritySubmenuParentRef) return;
      this.clearClosePrioritySubmenuTimer();
      this.prioritySubmenu.visible = true;

      this.$nextTick(() => {
        if (!this.$refs.prioritySubmenuParentRef || !this.$refs.prioritySubmenuRef) {
          this.prioritySubmenu.visible = false;
          return;
        }
        const parentRect = this.$refs.prioritySubmenuParentRef.getBoundingClientRect();
        const submenuDimensions = this.prioritySubmenu.dimensions;
        const { top, left, positionedRight } = calculateSubmenuPosition(parentRect, submenuDimensions);
        
        this.prioritySubmenu.style = { top: `${top}px`, left: `${left}px` };
        this.prioritySubmenu.isPositionedLeft = !positionedRight;
        console.log(`[CollectionBoxView] openPrioritySubmenu: Submenu at T:${top}, L:${left}. Positioned Right: ${positionedRight}`);
      });
    },
    scheduleClosePrioritySubmenu(isMouseLeaveFromSubmenu = false) {
      this.clearClosePrioritySubmenuTimer();
      this.prioritySubmenu.closeTimer = setTimeout(() => {
        this.prioritySubmenu.visible = false;
      }, isMouseLeaveFromSubmenu ? 50 : 150);
    },
    clearClosePrioritySubmenuTimer() {
      if (this.prioritySubmenu.closeTimer) {
        clearTimeout(this.prioritySubmenu.closeTimer);
        this.prioritySubmenu.closeTimer = null;
      }
    },
    setCollectionContextMenuTodoPriority(priority) {
      if (this.collectionContextMenu.selectedTodo) {
        console.log('[CollectionBoxView] 更新收件箱待办事项优先级:', this.collectionContextMenu.selectedTodo.id, priority);
        this.updateTodoPriority({ 
          todoId: this.collectionContextMenu.selectedTodo.id, 
          priority,
          source: 'inbox'
        });
      }
      this.closeCollectionContextMenu();
    },
    assignDateFromCollectionContextMenu() {
      if (this.collectionContextMenu.selectedTodo) {
        this.datePickerTargetTodoId = this.collectionContextMenu.selectedTodo.id;
        this.datePickerInitialDate = new Date();
        if (this.$refs.inboxMiniCalendar) {
          this.$refs.inboxMiniCalendar.open(this.$refs.collectionContextMenuRef);
        }
      }
      this.closeCollectionContextMenu();
    },
    editCollectionContextTodo() {
      if (this.collectionContextMenu.selectedTodo) {
        this.startEditing(this.collectionContextMenu.selectedTodo);
      }
      this.closeCollectionContextMenu();
    },
    archiveCollectionContextTodo() {
      if (this.collectionContextMenu.selectedTodo) {
        this.archiveInboxTodo({ todoId: this.collectionContextMenu.selectedTodo.id });
      }
      this.closeCollectionContextMenu();
    },
    deleteCollectionContextTodo() {
      if (this.collectionContextMenu.selectedTodo) {
        this.deleteInboxTodo(this.collectionContextMenu.selectedTodo.id);
      }
      this.closeCollectionContextMenu();
    },
    // Pagination methods for Inbox
    goToInboxPage(pageNumber) {
      if (pageNumber >= 1 && pageNumber <= this.totalPagesInbox) {
        this.currentPageInbox = pageNumber;
      }
    },
    prevInboxPage() {
      if (this.currentPageInbox > 1) {
        this.currentPageInbox--;
      }
    },
    nextInboxPage() {
      if (this.currentPageInbox < this.totalPagesInbox) {
        this.currentPageInbox++;
      }
    },
  },
  directives: {
    focus: {
      inserted: function (el) {
        el.focus();
      },
      update: function(el, binding, vnode) {
        if (vnode.key === vnode.context.editingTodoId) {
             Vue.nextTick(() => el.focus());
        }
      }
    }
  },
  watch: {
    currentSortOrder() {
      this.selectedTodoIds = [];
      this.currentPageInbox = 1;
    },
    filterStatus() {
      this.selectedTodoIds = [];
      this.currentPageInbox = 1;
    },
    searchQueryInbox() {
      this.currentPageInbox = 1;
      // selectedTodoIds are not cleared here intentionally, 
      // so selections can persist across minor search adjustments if desired.
      // If clearing selection on search is preferred, add: this.selectedTodoIds = [];
    },
    totalPagesInbox(newTotal) {
      if (this.currentPageInbox > newTotal && newTotal > 0) {
        this.currentPageInbox = newTotal;
      } else if (newTotal === 0) {
        this.currentPageInbox = 1;
      }
    },
    getInboxTodos: {
        handler() {
            // When the base list of todos changes (e.g., after adding/deleting), 
            // reset to the first page if the current page becomes invalid.
            // This is implicitly handled by totalPagesInbox watcher in most cases.
            // No need to clear selectedTodoIds here, as they might still be relevant.
        },
        deep: true
    },
    filterPriorityInbox(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.currentPageInbox = 1;
      }
    },
  },
  created() {
    // Attempt to fetch inbox todos when the component is created
    if (typeof this.fetchInboxTodos === 'function') {
      this.fetchInboxTodos().catch(error => {
        console.error('[CollectionBoxView.vue] Error fetching inbox todos on created:', error);
      });
    } else {
      console.warn('[CollectionBoxView.vue] fetchInboxTodos action is not mapped or defined. Inbox todos might not load.');
    }
    console.log('[CollectionBoxView.vue] Component created at', new Date().toISOString());
  },
  beforeDestroy() {
  }
}
</script>

<style scoped>
.collection-box-view-content {
  padding: 0; /* Assuming MainLayout's .content-area provides padding */
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: var(--theme-bg-content-area);
  color: var(--theme-text-primary);
  gap: var(--spacing-base); /* Added consistent gap */
}

.add-todo-solo-section {
  display: flex;
  gap: var(--spacing-md);
  padding: var(--spacing-base) var(--spacing-base) 0; /* No bottom padding, handled by view gap */
  background-color: var(--theme-bg-content-area); /* Match content area */
  flex-shrink: 0;
}

  .todo-input {
    flex-grow: 1;
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--theme-bg-input);
  color: var(--theme-text-primary);
  border: var(--border-width) var(--border-style) var(--theme-border-primary);
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-base);
}
.todo-input::placeholder { color: var(--theme-text-muted); }
.todo-input:focus {
  border-color: var(--theme-accent-primary);
  box-shadow: 0 0 0 3px rgba(var(--theme-accent-primary-rgb), 0.3);
  }

  .add-button {
  padding: var(--spacing-sm) var(--spacing-lg); /* More horizontal padding */
  background: var(--theme-accent-gradient);
  color: var(--theme-text-primary); /* Adjusted for light blue/white gradient */
    border: none;
  border-radius: var(--border-radius-base);
    cursor: pointer;
  transition: filter var(--transition-duration-short), box-shadow var(--transition-duration-short);
  white-space: nowrap;
  font-weight: var(--font-weight-medium);
}
.add-button:hover {
  filter: brightness(1.1);
  box-shadow: 0 2px 8px rgba(var(--theme-accent-primary-rgb), 0.2);
    }
.add-button:active {
  filter: brightness(0.95);
    }

.search-section-inbox {
  padding: 0 var(--spacing-base); /* No top/bottom padding, handled by view gap */
  flex-shrink: 0;
}

.search-input-inbox {
  width: 100%;
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--theme-bg-input);
  color: var(--theme-text-primary);
  border: var(--border-width) var(--border-style) var(--theme-border-primary);
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-base);
}
.search-input-inbox::placeholder { color: var(--theme-text-muted); }
.search-input-inbox:focus {
  border-color: var(--theme-accent-primary);
  box-shadow: 0 0 0 3px rgba(var(--theme-accent-primary-rgb), 0.3);
}

.controls-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-sm) var(--spacing-base);
  background-color: var(--theme-bg-secondary);
  border-top: var(--border-width) var(--border-style) var(--theme-border-primary);
  border-bottom: var(--border-width) var(--border-style) var(--theme-border-primary);
  flex-shrink: 0;
  gap: var(--spacing-md);
}

.batch-actions-left, .filter-sort-controls {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  }

.filter-controls, .sort-controls, .filter-priority-controls {
    display: flex;
    align-items: center;
  gap: var(--spacing-sm);
  white-space: nowrap; /* Prevent wrapping of label and select box */
}

.controls-label {
  font-size: var(--font-size-sm);
  color: var(--theme-text-secondary);
  margin-right: var(--spacing-xs);
    }

.filter-controls button, .filter-priority-controls button {
  padding: var(--spacing-xs) var(--spacing-sm);
  background-color: var(--theme-bg-button-secondary);
  color: var(--theme-text-secondary);
  border: var(--border-width) var(--border-style) var(--theme-border-secondary);
  border-radius: var(--border-radius-base);
  cursor: pointer;
  transition: all var(--transition-duration-short);
  font-size: var(--font-size-sm); /* Ensure consistent font size */
  display: flex; /* For aligning dot and text */
  align-items: center; /* For aligning dot and text */
  gap: var(--spacing-xs); /* For aligning dot and text */
    }
.filter-controls button:hover, .filter-priority-controls button:hover {
  border-color: var(--theme-accent-primary);
  color: var(--theme-accent-primary);
    }
.filter-controls button.active, .filter-priority-controls button.active {
  background: var(--theme-accent-gradient);
  color: var(--theme-text-primary); /* Adjusted for light blue/white gradient */
  border-color: transparent;
  font-weight: var(--font-weight-medium);
}

/* Styling for priority dots within filter buttons, if not already covered by a global style */
.filter-priority-controls button .priority-dot-filter {
  width: 10px;
  height: 10px;
  border-radius: var(--border-radius-circle);
  flex-shrink: 0;
}

.filter-priority-controls button.active .priority-dot-filter {
  /* Optional: Add a border to the dot if its color clashes with active button background */
   border: 1px solid rgba(0,0,0,0.1); 
}

.select-all-checkbox { /* Copied from CalendarView and adapted */
  appearance: none; -webkit-appearance: none; width: 18px; height: 18px;
  border: var(--border-width) var(--border-style) var(--theme-border-primary);
  border-radius: var(--border-radius-sm); background-color: var(--theme-bg-input);
  cursor: pointer; position: relative; flex-shrink: 0;
  transition: background-color var(--transition-duration-short), border-color var(--transition-duration-short);
}
.select-all-checkbox:checked {
  background: var(--theme-accent-primary); border-color: transparent;
}
.select-all-checkbox:checked::after {
  content: ''; position: absolute; left: 6px; top: 3px; width: 5px; height: 10px;
  border: solid var(--theme-text-on-accent); border-width: 0 2px 2px 0; transform: rotate(45deg);
}
.select-all-checkbox:focus {
  outline: none; box-shadow: 0 0 0 2px rgba(var(--theme-accent-primary-rgb), 0.3);
    }
.select-all-label {
  color: var(--theme-text-secondary); cursor: pointer; font-size: var(--font-size-sm); user-select: none;
    }

.batch-action-button { /* Copied from CalendarView and adapted */
  padding: var(--spacing-xs) var(--spacing-sm); font-size: var(--font-size-sm);
  color: var(--theme-text-secondary); background-color: var(--theme-bg-button-secondary);
  border: var(--border-width) var(--border-style) var(--theme-border-secondary);
  border-radius: var(--border-radius-base); cursor: pointer;
  transition: all var(--transition-duration-short); display: flex; align-items: center; gap: var(--spacing-xs);
}
.batch-action-button .button-icon {
  font-family: var(--font-family-icons); font-size: var(--font-size-base);
}
.batch-action-button:hover:not(:disabled) {
  background-color: var(--theme-bg-hover); color: var(--theme-text-primary); border-color: var(--theme-border-primary);
  }
.batch-action-button:disabled {
  color: var(--theme-text-disabled); background-color: color-mix(in srgb, var(--theme-bg-button-secondary) 50%, transparent);
  border-color: var(--theme-border-primary); cursor: not-allowed;
}
.batch-action-button.delete:hover:not(:disabled) {
  background-color: #B91C1C; color: var(--theme-text-on-accent); border-color: #991B1B;
}
.batch-action-button.archive:hover:not(:disabled) { /* Added distinct hover for archive */
  background-color: #5856d6; color: var(--theme-text-on-accent); border-color: #403fa6;
}

.todo-list-section {
  flex-grow: 1;
  overflow-y: auto;
  padding: 0 var(--spacing-base) var(--spacing-base); /* Add padding to match other sections */
  background-color: var(--theme-bg-content-area);
}

.todo-list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
}

  .todo-item {
    display: flex;
    align-items: center;
  padding: var(--spacing-md);
  background-color: var(--theme-bg-card);
  border-bottom: var(--border-width) var(--border-style) var(--theme-border-primary);
  transition: background-color var(--transition-duration-short), border-color var(--transition-duration-short);
  gap: var(--spacing-md);
}
.todo-item:first-child { /* Add top border to the first item if list is within a padded container */
    border-top: var(--border-width) var(--border-style) var(--theme-border-primary);
}
.todo-item:hover {
  background-color: var(--theme-bg-hover);
  border-color: var(--theme-border-secondary); /* Lighter border on hover */
}
.todo-item.selected-for-batch {
  background-color: color-mix(in srgb, var(--theme-accent-primary) 20%, var(--theme-bg-card));
  border-color: var(--theme-accent-primary);
    }

.todo-select-checkbox { /* Copied from CalendarView and adapted */
  appearance: none; -webkit-appearance: none; width: 18px; height: 18px;
  border: var(--border-width) var(--border-style) var(--theme-border-primary);
  border-radius: var(--border-radius-sm); background-color: var(--theme-bg-input);
  cursor: pointer; position: relative; flex-shrink: 0;
  transition: background-color var(--transition-duration-short), border-color var(--transition-duration-short);
}
.todo-select-checkbox:checked {
  background: var(--theme-accent-primary); border-color: transparent;
      }
.todo-select-checkbox:checked::after {
  content: ''; position: absolute; left: 6px; top: 3px; width: 5px; height: 10px;
  border: solid var(--theme-text-on-accent); border-width: 0 2px 2px 0; transform: rotate(45deg);
}
.todo-select-checkbox:focus {
  outline: none; box-shadow: 0 0 0 2px rgba(var(--theme-accent-primary-rgb), 0.3);
    }

.todo-status-icon { /* Copied from CalendarView and adapted */
  font-family: var(--font-family-icons); font-size: var(--font-size-lg);
  cursor: pointer; color: var(--theme-text-secondary);
  transition: color var(--transition-duration-short); padding: var(--spacing-xs);
  border-radius: var(--border-radius-circle); line-height: 1;
}
.todo-status-icon:hover {
  color: var(--theme-text-primary); background-color: var(--theme-bg-hover);
}
.todo-status-icon.completed-icon { color: var(--theme-accent-primary); }
.todo-status-icon.completed-icon:hover { color: var(--theme-accent-highlight); }

.priority-indicator { /* Copied from CalendarView and adapted */
  width: 10px; height: 10px;
  border-radius: var(--border-radius-circle);
       flex-shrink: 0;
    }

    .todo-label {
      flex-grow: 1;
  color: var(--theme-text-primary);
  cursor: text;
  user-select: text;
  padding: var(--spacing-xs) 0;
  line-height: var(--line-height-base);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
      min-width: 0;
    }
.todo-item.completed .todo-label {
  color: var(--theme-text-muted);
  text-decoration: line-through;
  text-decoration-color: var(--theme-text-disabled);
}

.todo-edit-input { /* Copied from CalendarView and adapted */
  flex-grow: 1; padding: var(--spacing-xs) var(--spacing-md);
  background-color: var(--theme-bg-input); color: var(--theme-text-primary);
  border: var(--border-width) var(--border-style) var(--theme-border-primary);
  border-radius: var(--border-radius-base); font-size: var(--font-size-base); outline: none;
  line-height: var(--line-height-base);
  min-width: 0;
}
.todo-edit-input:focus {
  border-color: var(--theme-accent-primary); box-shadow: 0 0 0 3px rgba(var(--theme-accent-primary-rgb), 0.3);
}

.empty-list-message {
  text-align: center;
  padding: var(--spacing-xl) var(--spacing-base);
  color: var(--theme-text-muted);
  font-style: italic;
  margin-top: var(--spacing-lg);
}

.bottom-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-sm) var(--spacing-base);
  background-color: var(--theme-bg-secondary);
  border-top: var(--border-width) var(--border-style) var(--theme-border-primary);
  flex-shrink: 0;
}

  .status-text {
  font-size: var(--font-size-sm);
  color: var(--theme-text-muted);
}

.priority-legend-container { /* Copied from CalendarView and adapted */
  padding: 0;
  background-color: transparent;
}
.priority-legend {
  display: flex; align-items: center;
  justify-content: flex-end;
  gap: var(--spacing-md);
}
  .legend-item {
  display: flex; align-items: center;
  gap: var(--spacing-xs);
  font-size: var(--font-size-sm);
  color: var(--theme-text-muted);
  }
  .legend-dot {
  width: 10px; height: 10px;
  border-radius: var(--border-radius-circle);
}

.context-menu, .priority-submenu { /* Copied from CalendarView and adapted */
  position: fixed;
  z-index: 1000; /* Submenu should be higher if they can overlap */
  background-color: var(--theme-bg-tertiary);
  border: var(--border-width) var(--border-style) var(--theme-border-secondary);
  border-radius: var(--border-radius-base);
  box-shadow: 0 4px 12px rgba(var(--theme-shadow-color-rgb, var(--d-shadow-color-rgb)), var(--theme-shadow-opacity-strong, var(--d-shadow-opacity-strong))); /* Fallback for shadow */
  padding: var(--spacing-xs) 0;
}
.priority-submenu {
  z-index: 1001; /* Ensure submenu is above main context menu */
   min-width: 100px;
}
.context-menu {
  min-width: 160px;
}

.context-menu-item { /* Copied from CalendarView and adapted */
  display: flex; align-items: center; gap: var(--spacing-sm);
  padding: var(--spacing-xs) var(--spacing-sm);
  color: var(--theme-text-secondary);
  cursor: pointer; font-size: var(--font-size-sm);
  border: none; background-color: transparent;
  width: 100%; text-align: left;
  transition: background-color var(--transition-duration-short), color var(--transition-duration-short);
}
.context-menu-item:hover {
  background-color: var(--theme-bg-hover);
  color: var(--theme-text-primary);
  }
.context-menu-item .priority-dot {
  width: 10px; height: 10px;
  border-radius: var(--border-radius-circle);
  flex-shrink: 0;
  }
.priority-submenu-container { position: relative; }
  .submenu-arrow {
  font-family: var(--font-family-icons);
  margin-left: auto;
  font-size: calc(var(--font-size-sm) * 0.9);
}

/* Styles for CustomSelect if needed, or rely on its internal/global styles */
.sort-select-wrapper {
  /* Example: Adjust width or other container properties if necessary */
  min-width: 180px; 
  }

/* Ensure CustomSelect component itself uses theme variables if its styles are scoped here */
/* If CustomSelect.vue has its own <style scoped>, those need to be themed too. */
/* This is a placeholder to remind that child components also need theming. */
.controls-bar :deep(.custom-select-container .select-header) {
  background-color: var(--theme-bg-input);
  border: var(--border-width) var(--border-style) var(--theme-border-primary);
  color: var(--theme-text-primary);
}
.controls-bar :deep(.custom-select-container .select-header:hover) {
  border-color: var(--theme-accent-primary);
}
.controls-bar :deep(.custom-select-container .options-list) {
  background-color: var(--theme-bg-tertiary);
  border: var(--border-width) var(--border-style) var(--theme-border-secondary);
}
.controls-bar :deep(.custom-select-container .option-item:hover) {
  background-color: var(--theme-bg-hover);
  color: var(--theme-text-primary);
}
.controls-bar :deep(.custom-select-container .option-item.selected) {
  background-color: var(--theme-accent-primary);
  color: var(--theme-text-on-accent);
  }

.pagination-controls-inbox {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: var(--spacing-base) 0;
  gap: var(--spacing-md);
  flex-shrink: 0;
  /* Assuming bottom-bar provides its own top border if needed */
  /* background-color: var(--theme-bg-secondary); */ /* Optional: match bottom-bar or content area */
}

.pagination-button-inbox {
  padding: var(--spacing-xs) var(--spacing-sm);
  background-color: var(--theme-bg-button-secondary);
  color: var(--theme-text-secondary);
  border: var(--border-width) var(--border-style) var(--theme-border-secondary);
  border-radius: var(--border-radius-base);
  cursor: pointer;
  transition: all var(--transition-duration-short);
}
.pagination-button-inbox:hover:not(:disabled) {
  background-color: var(--theme-bg-hover);
  color: var(--theme-text-primary);
  border-color: var(--theme-border-primary);
}
.pagination-button-inbox:disabled {
  color: var(--theme-text-disabled);
  background-color: color-mix(in srgb, var(--theme-bg-button-secondary) 50%, transparent);
  border-color: var(--theme-border-primary);
  cursor: not-allowed;
}
.pagination-info-inbox {
  font-size: var(--font-size-sm);
  color: var(--theme-text-muted);
}

</style> 